package lib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MyPdf2swf {
	private static String toolsDir = "D:\\Program Files\\SWFTools\\";
	private static String convertCMD = "pdf2swf.exe \"{path.pdf}{pdffile}\" -o \"{path.swf}{pdffile}.swf\" -f -T 9 -t -s storeallcharacters -s linknameurl";
	private static Map<String,String> config = new HashMap<String,String>();
	
	static{
		config.put("path.pdf","E:\\pdf\\");
		config.put("path.swf","E:\\swf\\");
	}
	
	public static ArrayList<String> commandLineAsList(String commandLine) {
		ArrayList<String> commands = new ArrayList<String>();
		String elt = "";
		boolean insideString = false;

		for (int i = 0; i < commandLine.length(); i++) {
			char c = commandLine.charAt(i);

			if (!insideString && (c == ' ' || c == '\t')) {
				if (elt.length() > 0) {
					commands.add(elt);
					elt = "";
				}
				continue;
			} else if (c == '"') {
				insideString = !insideString;
			}

			elt += c;
		}
		if (elt.length() > 0) {
			commands.add(elt);
		}

		return commands;
	}
	
	public static String execs(String execString) {
		String ret = "";
		try {
			ArrayList<String> commands = commandLineAsList(execString);

			ProcessBuilder pb = new ProcessBuilder(commands);
			pb.redirectErrorStream(true);
			Process p = pb.start();

			BufferedReader is = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = is.readLine()) != null) {
				ret += "	" + line;
			}
			try {
				p.waitFor();
			} catch (InterruptedException e) {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return ret;
	}
	
	public static void main(String[] args){
		String pdffile="2014.pdf";
		String cmd = toolsDir+convertCMD;
		cmd = cmd.replace("{path.pdf}", config.get("path.pdf"));
		cmd = cmd.replace("{path.swf}", config.get("path.swf"));
		cmd = cmd.replace("{pdffile}", pdffile);
//		String ROOT = System.getProperty("user.home");
//		String OS = System.getProperty("os.name");
//		String DIRECTORY_SEPARATOR	= System.getProperty("file.separator");
//		System.out.println();
		System.out.println(execs(cmd));
	}
}
